// pages/voice2text/index.js
const app = getApp();

//引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

import errorCode from '../../assets/data/errCode'
import res from '../../assets/data/resAI'

var myBehavior = require('../../behavior/my-behavior')

let questionArrs = new Array()
for (let index = 0; index < 15; index++) {
  questionArrs.push(index + 1)
}


Page({
  behaviors: [myBehavior],
 
  /**
   * 页面的初始数据
   */
  data: {
    //语音
    recordState: false, //录音状态
    content:'',//识别的内容
    text: '皮肤看起来还挺光滑哒，不过还有提升空间哈，平时做好补水保湿，补充肌肤所需营养，可以让皮肤看起来更加有光泽感~',
    list: [
      {content: questionArrs.slice(0,5), flag: ''},
    ],
    isDisabled: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('load');
    //识别语音
    this.initRecord();
  },



  onShow(){
    // 获取录音授权
    // this.getRecordAuth()
    // this.playTextToVoice(this.data.text)
    // 选择器数组  是否减去控制高
    this.getRect(['.form-field'])
  },

  // 权限询问
  getRecordAuth() {
    wx.getSetting({
      success: (res) => {
        console.log("succ")
        console.log(res)
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
                // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                console.log("succ auth")
            }, fail: () => {
                console.log("fail auth")
                // this.touchStart()
                // return
                this.userAuthFail('scope.record', '请授权录音服务，用于获取语音识别').then(authRecordRes => {
                  console.log(authRecordRes);
                }).catch(authRecordErr => {
                  console.log(authRecordErr);
                  wx.showToast({
                    title: authRecordErr,
                    icon: 'none',
                    duration: 2000,
                  })
                })
            }
          })
        } else {
          console.log("record has been authed")
        }
      }, fail(res) {
          console.log("fail")
          console.log(res)
      }
    })
  },

    /**
  * 用户拒绝授权
  * @param {string} scope 需授权的权限
  * @param {string} tip 权限对应的提示
  */
  userAuthFail(scope, tip) {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '提示',
        content: tip,
        confirmText: '去授权',
        cancelText: '不授权',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                resolve(res.authSetting[scope])
              }
            })
          }
          if (res.cancel) {
            reject('您拒绝了授权')
          }
        },
      })
    })
  },

  // 手动输入内容
  conInput(e) {
    this.setData({
      content:e.detail.value,
    })
    // !this.data.recordState && setTimeout(() => {
    //   if (this.innerAudioContext) {
    //     this.innerAudioContext.stop()
    //     this.innerAudioContext.destroy()
    //   }
    //   this.playTextToVoice(this.data.content)
    // }, 3000)
  },

  selectContentItem(e){
    const {contentItem:content} = e.mark
    this.setData({
      list: [...this.data.list, {content: content, flag: 'question'}],
      isDisabled: true
    })
    wx.showLoading({
      title: '正在处理',
      mask: true
    })
    setTimeout(() => {
      console.log(res);
      const index = Math.floor(Math.random() * (res.length - 1))
      this.setData({
        list: [...this.data.list, {content: res[index], flag: 'answer'}],
        content: '',
        isDisabled: false,
      })
      wx.hideLoading()
    }, 3000)
    console.log('发送');
  },

  changeQuestion(){
    const arr = [0,1,2]

    const flagEmpty = this.data.list.findIndex(item => item.flag === '')

    const startIndex = parseInt(Math.random() * arr.length) * 5
    this.data.list[flagEmpty].content = questionArrs.slice(startIndex,startIndex + 5)

    this.setData({
      list: this.data.list
    })

  },

  /**表单提交 */
  formSubmit(e){
    console.log(e);
    const {content} = e.detail.value
    console.log(content);
    if (content === '') {
      wx.showToast({
        title: '发送内容不能为空',
        icon: 'none'
      })
      return
    }
    this.setData({
      list: [...this.data.list, {content: content, flag: 'question'}],
      isDisabled: true
    })
    wx.showLoading({
      title: '正在处理',
      mask: true
    })
    setTimeout(() => {
      console.log(res);
      const index = Math.floor(Math.random() * (res.length - 1))
      this.setData({
        list: [...this.data.list, {content: res[index], flag: 'answer'}],
        content: '',
        isDisabled: false,
      })
      wx.hideLoading()
    }, 3000)
    console.log('发送');
  },

  //识别语音 -- 初始化
  initRecord() {
    const that = this;
    // 有新的识别内容返回，则会调用此事件
    manager.onRecognize = function (res) {
      console.log('有新的识别内容');
      console.log(res)
      if (res.result === '') return
      const text = that.data.content + res.result
      that.setData({
        content: text
      })
    }
    // 正常开始录音识别时会调用此事件
    manager.onStart = function (res) {
      console.log("成功开始识别", res)
    }
    // 识别错误事件
    manager.onError = function (res) {
      console.error("error msg", res)
      const err = errorCode.filter(item => item.retcode === res.retcode)[0]
      const { retcode, text, title, icon } = err
      console.log(text);
      title !== '' && wx.showToast({
        title,
        icon
      })
      // if (retcode === -30011) {
      //   that.setData({
      //     recordState: false
      //   })
      //   // 语音结束识别
      //   manager.stop();
      // }
    }
    //识别结束事件
    manager.onStop = function (res) {
      console.log('------结束-------')
      console.log(res);
      console.log('录音临时文件地址 -->' + res.tempFilePath); 
      console.log('录音总时长 -->' + res.duration + 'ms'); 
      console.log('文件大小 --> ' + res.fileSize + 'B');
      console.log('语音内容 --> ' + res.result);
      if (res.result == '') {
        // that.playTextToVoice('我没有听清楚，请重新说一遍！')
        wx.showModal({
          title: '我没有听清楚，请重新说一遍！',
        })
        return;
      }
      var text = that.data.content + res.result;
      that.setData({
        content: text
      })


      // !that.data.recordState && setTimeout(() => {
      //   that.playTextToVoice(text)
      // }, 3000)
    }

  },
  //语音  --按住说话
  touchStart(e) {
    console.log('start');
    // 防止 -30011
    if (this.data.recordState) return
    this.setData({
      recordState: true  //录音状态
    })
    // 语音开始识别
    manager.start({
      lang: 'zh_CN',// 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    })
  },
  //语音  --松开结束
  touchEnd(e) {
    console.log('end');
    // 防止重复触发stop函数 -30012
    if(!this.data.recordState) {
      console.warn("has finished!")
      return
    }
    this.setData({
      recordState: false
    })
    // 语音结束识别
    manager.stop();
  },

  tapPlay(e){
    const {content: text} = e.currentTarget.dataset
    this.innerAudioContext && this.innerAudioContext.stop()
    this.playTextToVoice(text)
  },

  // 文字转语音--语音合成
  playTextToVoice(content){
    //创建内部 audio 上下文 InnerAudioContext 对象。
    this.innerAudioContext = wx.createInnerAudioContext();
    const that = this;
    plugin.textToSpeech({
      // 调用插件的方法
      lang: 'zh_CN',
      // lang: 'en_US',
      content,
      success: (res) => {
        // that.playAudio(res.filename);
        this.innerAudioContext.src = res.filename; //设置音频地址
        this.innerAudioContext.play(); //播放音频
      }
    });
  },



  // 播报语音
  playAudio(e) {
    this.innerAudioContext.src = e; //设置音频地址
    this.innerAudioContext.play(); //播放音频
  },

    /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.innerAudioContext && this.innerAudioContext.stop();
    this.innerAudioContext && this.innerAudioContext.destroy();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(){
    this.innerAudioContext && this.innerAudioContext.stop();
    this.innerAudioContext && this.innerAudioContext.destroy();
  }
})